package org.lyfeng.spring.beans.factory.support;

import java.lang.reflect.Field;
import org.lyfeng.spring.beans.annotation.Autowired;
import org.lyfeng.spring.beans.definitions.AutowireBeanDefinition;
import org.lyfeng.spring.beans.factory.config.AutowireBeanFactory;
import org.lyfeng.spring.context.annotation.ClassPathBeanDefinitionScanner;
import org.lyfeng.spring.context.annotation.Scanner;
import org.lyfeng.spring.exception.BeansExceptions;

public class AutowireBeanFactoryImpl extends AbstractBeanFactory
		implements AutowireBeanFactory {
	private Scanner scanner=new ClassPathBeanDefinitionScanner(this);

	protected void autowiredByType(AutowireBeanDefinition autowireBeanDefinition)
	{
//		String beanName=autowireBeanDefinition.getBeanName();
//		Object beanObject=super.getBean(beanName);
//		Set<String> properties=autowireBeanDefinition.getProperties();
	}
	protected void autowiredByName(AutowireBeanDefinition autowireBeanDefinition)
	{
		String beanName = autowireBeanDefinition.getBeanName();
		/** target bean **/
		Object beanObject = super.getBean(beanName);
//		Set<PropertyValue> properties = autowireBeanDefinition.getProperties();
		/** 注入到target bean中的object **/
//		Object autowireObj = this.getBean(p.getRefBean());
		// 执行注入操作
		Field[] fields = beanObject.getClass().getFields();
		for (Field f : fields) {
			if (null != f.getAnnotation(Autowired.class)) {
				String fieldName=f.getName();
				System.out.println(String.format("fieldName is %s",fieldName));
				Object autowireObj=super.getBean(fieldName);
				f.setAccessible(true);
				try {
					f.set(beanObject,autowireObj);
				} catch (IllegalArgumentException | IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * bean创建执行的初始化方法
	 */
	@Override
	public Object initializeBean(Object existingBean, String beanName)
			throws BeansExceptions {
		// TODO Auto-generated method stub
		return null;
	}
	/**
	 * scan某目录下加载所有的class文件
	 */
	@Override
	public void scan(String... besePackages) {
		// TODO Auto-generated method stub
		scanner.scan(this.getClass().getClassLoader(), besePackages);
	}

	/**
	 * autowire by name
	 */
	@Override
	public void autowireBean(Object target, Object injectedBean, String field)
			throws BeansExceptions {
		// TODO Auto-generated method stub
		try {
			Field injectField=target.getClass().getDeclaredField(field);
			injectField.setAccessible(true);
			injectField.set(target, injectedBean);
		} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
